<!DOCTYPE html>
<html>
<head>
    <title>WebSocket 翻译客户端</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        #controls {
            margin-bottom: 20px;
        }
        button {
            padding: 8px 16px;
            margin-right: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        #results {
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 4px;
            background-color: #f9f9f9;
        }
        h2 {
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .result-section {
            margin-bottom: 15px;
        }
        .error {
            color: red;
        }
    </style>
</head>
<body>
<h1>实时翻译客户端</h1>

<div id="controls">
    <button id="connectBtn">连接 WebSocket</button>
    <button id="disconnectBtn" disabled>断开连接</button>
    <div>
        <label for="serverUrl">服务器地址:</label>
        <input type="text" id="serverUrl" value="ws://127.0.0.1:8079/api/v1/ai/gummy" style="width: 300px;">
    </div>
</div>

<div id="results">
    <h2>识别结果</h2>
    <div class="result-section">
        <h3>转录文本:</h3>
        <div id="transcription" style="min-height: 50px; border: 1px solid #eee; padding: 10px;"></div>
    </div>

    <div class="result-section">
        <h3>翻译结果:</h3>
        <div id="translation" style="min-height: 50px; border: 1px solid #eee; padding: 10px;"></div>
    </div>
</div>

<div id="status" style="margin-top: 20px; color: #666;"></div>
<div id="error" class="error" style="margin-top: 10px;"></div>

<script>
    let socket;
    const connectBtn = document.getElementById('connectBtn');
    const disconnectBtn = document.getElementById('disconnectBtn');
    const statusDiv = document.getElementById('status');
    const errorDiv = document.getElementById('error');
    const serverUrlInput = document.getElementById('serverUrl');

    // 连接WebSocket
    connectBtn.addEventListener('click', () => {
        const serverUrl = serverUrlInput.value.trim();
        if (!serverUrl) {
            showError('请输入服务器地址');
            return;
        }

        statusDiv.textContent = "正在连接到服务器...";
        errorDiv.textContent = "";
        connectBtn.disabled = true;

        console.log(`尝试连接到: ${serverUrl}`);

        try {
            socket = new WebSocket(serverUrl);

            socket.onopen = function(e) {
                console.log('连接已建立');
                statusDiv.textContent = "已连接到服务器";
                disconnectBtn.disabled = false;
                showError('');

                // 可以在这里发送初始化消息
                // socket.send(JSON.stringify({type: "hello"}));
            };

            socket.onmessage = function(event) {
                console.log('收到数据:', event.data);
                try {
                    const data = JSON.parse(event.data);
                    console.log('解析后的数据:', data);

                    // 更新UI
                    if (data.transcription) {
                        document.getElementById('transcription').innerText = data.transcription;
                    }

                    if (data.translations && data.translations.length > 0) {
                        document.getElementById('translation').innerText = data.translations.join('\n');
                    }

                    if (data.is_final) {
                        console.log('任务完成');
                        statusDiv.textContent = "任务已完成";
                        socket.close();
                    }

                    if (data.error) {
                        showError('服务器返回错误: ' + data.error);
                    }
                } catch (e) {
                    console.error('解析消息失败:', e);
                    showError('解析消息失败: ' + e.message);
                    document.getElementById('transcription').innerText = "无法解析服务器响应: " + event.data;
                }
            };

            socket.onclose = function(event) {
                console.log('关闭事件:', event);
                if (event.wasClean) {
                    statusDiv.textContent = `连接已关闭，代码=${event.code} 原因=${event.reason || '无'}`;
                } else {
                    statusDiv.textContent = "连接意外中断";
                    showError('连接中断: ' + (event.reason || '未知原因'));
                }
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
            };

            socket.onerror = function(error) {
                console.error('WebSocket错误:', error);
                showError('连接错误: ' + (error.message || '未知错误'));
                statusDiv.textContent = "连接发生错误";
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
            };
        } catch (e) {
            showError('创建WebSocket失败: ' + e.message);
            connectBtn.disabled = false;
            console.error('创建WebSocket异常:', e);
        }
    });

    // 断开连接
    disconnectBtn.addEventListener('click', () => {
        if (socket) {
            socket.close();
        }
    });

    function showError(message) {
        errorDiv.textContent = message;
        if (message) {
            console.error(message);
        }
    }
</script>
</body>
</html>